package com.calligraphy.bases.utils;

import org.apache.tomcat.util.codec.binary.Base64;
import sun.misc.BASE64Decoder;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * @Author hy
 * @Date 2018/12/14 9:45
 **/
public class AESUtil {

	private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
	private static final String KEY_ALGORITHM = "AES";
	private static final String PASSWORD = "1234567890123456";

	/**
	 * AES 加密操作
	 *
	 * @param content	待加密内容
	 * @return 返回Base64 转码后的加密数据
	 */
	public static String encryptData(String content) {
		try {
			Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
			byte[] byteContent = content.getBytes("utf-8");
			SecretKeySpec secreKeySpec = new SecretKeySpec(PASSWORD.getBytes(), KEY_ALGORITHM);
			cipher.init(Cipher.ENCRYPT_MODE, secreKeySpec);
			byte[] result = cipher.doFinal(byteContent);
			return Base64.encodeBase64String(result);
		} catch (Exception ex) {
			return "";
		}
	}

	/**
	 * AES 解密操作
	 * 
	 * @param encrypted
	 * @return
	 */
	public static String decryptData(String encrypted) {
		try {
			byte[] byteMi = new BASE64Decoder().decodeBuffer(encrypted);
			SecretKeySpec key = new SecretKeySpec(PASSWORD.getBytes(), KEY_ALGORITHM);
			Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
			cipher.init(Cipher.DECRYPT_MODE, key);
			byte[] decryptedData = cipher.doFinal(byteMi);
			return new String(decryptedData, "UTF-8");
		} catch (Exception e) {
			return "-1";
		}
	}


}
